<template>
  <div class="auto">
    <validator name='m'>
      <meter-message :metermessage.sync="model.metermessage" @valid="meterinfo = true"
                     @invalid="meterinfo = false"></meter-message>
      <form novalidate class="form-horizontal">
        <div class="row" style="margin-top:10px;">
          <label for="f_changemeter_type" class=" col-sm-2 control-label">换表类型:</label>
          <div class="col-sm-2">
            <v-select id="f_changemeter_type"
                      v-model="model.f_changemeter_type"
                      placeholder='请选择'
                      :value.sync="model.f_changemeter_type"
                      :options='replacewatchtype'
                      close-on-select clear-button>
            </v-select>
          </div>
          <div v-if='money'>
            <label for="f_changemeter_fee" class=" col-sm-2 control-label">换表金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_changemeter_fee" placeholder="换表金额">
            </div>
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="gasTogas && row.f_newremanent_gas > 0">
          <label for="f_remanent_gas" class=" col-sm-2 control-label">剩余补气量:</label>
          <div class="col-sm-2">
            <input class="form-control" type="text" v-model="row.f_newremanent_gas"
                   placeholder="0" disabled>
          </div>
          <div v-if="row.f_newremanent_gas > 0">
            <label for="f_pregas" class=" col-sm-2 control-label">本次补气量:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_pregas" placeholder="本次补气量" disabled>
            </div>
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="gasToAmount && row.f_newremanent_gas > 0">
          <label for="f_remanent_amount" class=" col-sm-2 control-label">剩余补气量:</label>
          <div class="col-sm-2">
            <input class="form-control" type="text" v-model="row.f_newremanent_gas"
                   placeholder="0" disabled>
          </div>
          <label for="f_remanent_amount" class=" col-sm-2 control-label">气价:</label>
          <div class="col-sm-2">
            <input class="form-control" type="number" v-model="model.f_price">
          </div>
          <label for="f_remanent_amount" class=" col-sm-2 control-label">剩余补气金额:</label>
          <div class="col-sm-2">
            <input class="form-control" type="text" v-model="(row.f_newremanent_gas * model.f_price).toFixed(2)"
                   placeholder="0" disabled>
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="amountToAmount">
          <label for="f_remanent_amount" class=" col-sm-2 control-label">剩余补气金额:</label>
          <div class="col-sm-2">
            <input class="form-control" type="text" v-model="row.f_newremanent_amount"
                   placeholder="0" disabled>
          </div>
          <div v-if="row.f_newremanent_amount > 0">
            <label for="f_preamount" class=" col-sm-2 control-label">本次补气金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_preamount" placeholder="本次补气金额" disabled>
            </div>
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="amountinfo">
          <label for="f_remanent_amount" class=" col-sm-2 control-label">剩余金额:</label>
          <div class="col-sm-2">
            <input class="form-control" type="text" v-model="row.f_newremanent_amount"
                   placeholder="0" disabled>
          </div>
          <div v-if="row.f_newremanent_amount > 0">
            <label for="f_preamount" class=" col-sm-2 control-label">存入账户金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_preamount" placeholder="本次补气金额" disabled>
            </div>
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <label for="f_change_operator" class=" col-sm-2 control-label">换表人:</label>
          <div class="col-sm-2">
            <!-- <input class="form-control" type="text" v-model="model.f_change_operator" placeholder="换表人"> -->
            <v-select id="f_change_operator"
                      v-model="model.f_change_operator"
                      placeholder='换表人'
                      :value.sync="model.f_change_operator"
                      :options='changepersons'
                      close-on-select></v-select>
          </div>
          <label for="f_changemeter_date" class=" col-sm-2 control-label">换表时间:</label>
          <div class="col-sm-2">
            <datepicker placeholder="换表时间"
                        v-model="model.f_changemeter_date"
                        :value.sync="model.f_changemeter_date"
                        :format="'yyyy-MM-dd HH:mm:ss'"
            ></datepicker>
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <label for="f_reason" class=" col-sm-2 control-label">换表原因:</label>
          <div class="form-group col-sm-2 ">
            <v-select id="f_reason"
                      v-model="model.f_reason"
                      placeholder='换表原因'
                      :value.sync="model.f_reason"
                      :options='reason'
                      close-on-select></v-select>
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="model.f_reason[0] ==='其他'">
          <div class="col-sm-offset-2 col-sm-8">
            <textarea class="form-control" rows="3" v-model="model.f_othereason" placeholder="请填写换表原因"></textarea>
          </div>
        </div>
  </div>
  </form>
  </validator>
  <div style="text-align:right;height:auto;margin-top:10px;margin-right:50px;">
    <button class="btn btn-primary" @click="changeAndPlus()"
            v-if="model.metermessage.gasbrand[0].f_meter_type.includes('卡表') && !amountinfo && (row.f_newremanent_gas > 0 || row.f_newremanent_amount > 0)"
            :disabled='!(meterinfo && $m.valid)' style="width:120px;margin-left:20px;">
      <span class="glyphicon glyphicon-floppy-disk"></span>换表并补气
    </button>
    <button class="btn btn-primary" @click="confirm()" style="width:80px;margin-left:20px;" :disabled="!meterinfo"
            v-if="amountinfo || !model.metermessage.gasbrand[0].f_meter_type.includes('卡表') || (model.metermessage.gasbrand[0].f_meter_type.includes('卡表') && (parseFloat(row.f_newremanent_gas) === 0 || parseFloat(row.f_newremanent_amount) === 0))"
            id='ComprehenOperation-chaMet-chaNewMet-确认'>
      <span class="glyphicon glyphicon-floppy-disk"></span>确认
    </button>
    <button class="btn btn-primary" @click="clean()" style="width:80px;margin-left:20px;"
            id='ComprehenOperation-chaMet-chaNewMet-取消'>
      <span class="glyphicon glyphicon-cog"></span>取消
    </button>
  </div>
  </div>
</template>
<script>
  /**
   *换表管理
   *换新表信息
   */
  import AppData from '../../../../../stores/AppData'
  import * as Util from '../../../../Util'
  import co from 'co'

  let getPriceGen = function* (self) {
    let getPrices = yield self.$resetpost('rs/sql/getFirstPrice', {data: {f_price_id: self.row.f_price_id}}, {
      resolveMsg: null,
      rejectMsg: null
    })
    console.log('换表获取阶梯价格...', getPrices)
    self.model.f_price = getPrices.data[0].f_price
  }

  export default {
    data() {
      return {
        model: {
          metermessage: {
            gasbrand: '',
            gasmodel: '',
            // pricetype: '',
            f_inputtor: '',
            f_position: '室内',
            // pricename: '',
            // f_price_type: '',           // 气价表中，气价类型
            // f_price_name: '',           // 气价表中，气价名称
            // f_user_type: '',            // 气价表中，户档案中
            // f_gasproperties: '',         // 气价表中，用气性质
            f_meter_base: 0
          },
          f_changemeter_type: '换新表',
          f_reason: '控制器坏',
          f_changemeter_date: Util.toStandardTimeString(),
          f_changemeter_fee: AppData.getSingleValue('换表金额'),
          isCardMeter: false,
          isfillgas: false,
          f_pregas: 0,
          f_preamount: 0,
          f_price: 0,
          f_newbalance: 0,
          f_newremanent_gas: 0
        },
        meterinfo: false,
        money: true,
        gasTogas: false,
        gasToAmount: false,
        amountinfo: false,
        amountToAmount: false
      }
    },
    props: ['row'],
    ready() {
      console.log('换表看看有没有阶梯价..', this.row)
      this.getFirstPrice()
    },
    methods: {
      changeAndPlus() {
        this.$showMessage(`请确保你已经插入了${this.model.metermessage.gasbrand[0].f_meter_brand}的卡？`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            this.model.isfillgas = true
            if (this.model.metermessage.gasbrand[0].f_meter_type === '气量卡表') {
              if (this.row.f_meter_type === '气量卡表') {
                // 气量卡表换气量卡表  将剩余气量按一阶价格换算成金额（在气量卡表里面只供参考）
                this.model.f_preamount = ((this.model.f_pregas - 0) * (this.model.f_price - 0)).toFixed(2)
              }
              if (this.row.f_meter_type === '金额卡表') {
                this.model.f_newbalance = (this.model.f_newbalance - 0) + (this.model.f_preamount - 0)
              }
            }
            if (this.model.metermessage.gasbrand[0].f_meter_type === '金额卡表') {
              if (this.row.f_meter_type === '气量卡表') {
                // this.model.f_pregas = (this.model.f_pregas - 0)
                this.model.f_preamount = ((this.model.f_pregas - 0) * (this.model.f_price - 0)).toFixed(2)
              }
              if (this.row.f_meter_type === '金额卡表') {
                // 金额卡表换金额卡表， 将剩余金额按一阶价格换算成气量，（在金额卡表里面只供参考）
                this.model.f_pregas = ((this.model.f_preamount - 0) / (this.model.f_price - 0)).toFixed(2)
              }
            }
            console.log('换表内容，，', this.model, this.row)
            this.$ChangeMeterService.changeAndPlus(this.model, this.row)
              .then(
                (res) => this.$dispatch('success', '换新表', this.row, res)
              ).catch(
              (error) => this.$dispatch('error', '换新表', this.row, error)
            )
          }
        })
      },
      confirm() {
        if (this.model.metermessage.gasbrand[0].f_meter_type.includes('卡表')) {
          if (this.row.f_meter_type === '机表' && this.row.isHasOwe === true) {
            this.$showMessage('之前机表有欠费, 换成卡表欠费记录将无法缴纳，请先对之前的机表进行清欠!!', ['confirm', 'cancel']).then((res) => {
              this.$dispatch('refresh')
            })
          } else {
            this.$showMessage(`请确保你已经插入了${this.model.metermessage.gasbrand[0].f_meter_brand}的卡？`, ['confirm', 'cancel']).then((res) => {
              if (res === 'confirm') {
                if (this.row.f_meter_type === '金额卡表') {
                  this.model.f_newbalance = (this.model.f_newbalance - 0) + this.model.f_preamount
                }
                console.log('换表内容，，', this.model, this.row)
                this.$ChangeMeterService.changeNewMeter(this.model, this.row)
                  .then(
                    (res) => this.$dispatch('success', '换新表', this.row, res)
                  ).catch(
                  (error) => this.$dispatch('error', '换新表', this.row, error)
                )
              }
            })
          }
        } else {
          // console.log('新的账户结余，，，', this.row.f_newremanent_gas * this.model.f_price, this.model.f_preamount, this.row.f_meter_type)
          this.$ChangeMeterService.changeNewMeter(this.model, this.row)
            .then(
              (res) => this.$dispatch('success', '换新表', this.row, res)
            ).catch(
            (error) => this.$dispatch('error', '换新表', this.row, error)
          )
        }
      },
      clean() {
        this.$dispatch('success', '换表', this.row)
      },
      getFirstPrice() {
        let gen = getPriceGen(this)
        co(gen)
      }
    },
    watch: {
      'model.f_changemeter_type'(val) {
        if (val[0] === '换新表') {
          this.money = true
        } else {
          this.money = false
        }
      },
      'model.metermessage.gasbrand'(val) {
        // 防止f_remanent_gas的值发生变化
        // console.log('换表界面，，，，', this.row)
        if (val.length > 0 && val[0].f_meter_type.includes('卡表')) {
          // 只有是气量卡表的时候
          if (val[0].f_meter_type === '气量卡表') {
            if (this.row.f_meter_type === '气量卡表') {
              this.gasTogas = true
              this.amountinfo = false
              this.amountToAmount = false
              this.gasToAmount = false
              this.model.f_pregas = this.row.f_newremanent_gas
            } else {
              this.gasTogas = false
              this.amountToAmount = false
              this.gasToAmount = false
              this.amountinfo = true
              this.model.f_preamount = this.row.f_newremanent_amount
            }
          }

          if (val[0].f_meter_type === '金额卡表') {
            if (this.row.f_meter_type === '气量卡表') {
              this.gasTogas = false
              this.amountinfo = false
              this.amountToAmount = false
              this.gasToAmount = true
              this.model.f_pregas = this.row.f_newremanent_gas
            } else if (this.row.f_meter_type === '金额卡表') {
              this.gasTogas = false
              this.amountinfo = false
              this.amountToAmount = true
              this.gasToAmount = false
              this.model.f_preamount = this.row.f_newremanent_amount
            } else {
              this.gasTogas = false
              this.gasToAmount = false
              this.amountToAmount = false
              this.amountinfo = true
              this.model.f_preamount = this.row.f_newremanent_amount
            }
          }
          this.model.isCardMeter = true
          if (this.row.f_surplus) {
            this.model.newbalance = this.model.newbalance + this.row.f_surplus
          }
        } else if (val.length > 0) {
          if (this.row.f_meter_type === '气量卡表') {
            this.amountinfo = false
            this.gasToAmount = true
          } else if (this.row.f_meter_type === '金额卡表') {
            this.amountinfo = true
            this.gasToAmount = false
            this.model.f_preamount = this.row.f_newremanent_amount
          }
          this.gasTogas = false
          this.amountToAmount = false
          this.model.isCardMeter = false
          // 将剩余气量存入表档案中的剩余补气量
          if (this.row.f_surplus) {
            this.model.newbalance = this.model.newbalance + this.row.f_surplus
          }
        }
      }
    },
    computed: {
      replacewatchtype() {
        return AppData.getParam('换表类型')
      },
      reason() {
        return AppData.getParam('换表原因')
      },
      changepersons() {
        let rs = []
        if (Util.f.f_changemeterman.length > 0) {
          for (let i = 0; i < Util.f.f_changemeterman.length; i++) {
            let temp = {
              label: Util.f.f_changemeterman[i].name,
              value: Util.f.f_changemeterman[i].name
            }
            rs.push(temp)
          }
        }
        return rs
      },
      changefee() {
        return AppData.getSingleValue('换表金额')
      }
    }
  }
</script>
